<template>
  <div>
    <a-modal
      :visible.sync="showSlaConfigModal"
      title="SLA配置"
      :footer="null"
      @cancel="closeModal"
      :destroy-on-close="true"
      width="30vw"
    >
      <a-space style="justify-content: flex-end; width: 100%">
        <a-button
          size="small"
          type="primary"
          @click="createSlaConfig"
          ref="createSlaConfigBtn"
          :disabled="state.createSlaConfigBtnDisabled"
          :loading="state.loadingCreateSlaConfigBtn"
        >
          新增
        </a-button>
      </a-space>
      <div>
        <remote-table
          class="slaTable"
          ref="slaConfigTable"
          :show-selection="false"
          :has-export="false"
          :show-setting="false"
          :has-refresh="false"
          :has-reset="false"
          :has-action="true"
          :has-paginate="false"
          :row-key="(record, index) => index"
          :columns="updateNodeColumns"
          :sy="300"
          :y="300"
          interface-u-r-l="/todo/SLA/page"
          :column-width="{
            task: 450
          }"
        >
          <template slot="action" slot-scope="{ record }">
            <a-space>
              <a class="table-btns" @click="updateSlaConfig(record)"> 编辑 </a>
              <a-popconfirm
                title="是否删除该SLA配置?"
                ok-text="是"
                cancel-text="否"
                @confirm="deleteSlaConfig(record)"
                @cancel="deleteSlaConfigCancel"
              >
                <a class="table-btns" href="javascript:void(0)"> 删除 </a>
              </a-popconfirm>
            </a-space>
          </template>
        </remote-table>
      </div>
    </a-modal>
    <a-modal
      :visible.sync="state.showCreateSlaConfigModal"
      title="SLA配置"
      :footer="null"
      @cancel="state.showCreateSlaConfigModal = false"
      :destroy-on-close="true"
      width="30vw"
    >
      <a-form layout="inline">
        <a-row class="sla-type-form-item" :gutter="16">
          <a-col class="gutter-row" :span="24">
            <a-form-item label="流程类型：" style="width: 100%; display: flex">
              <a-select
                allow-clear
                v-model="state.slaType"
                placeholder="请选择"
                style="width: 100%"
              >
                <a-select-option
                  v-for="item in slaTypeOptions"
                  :key="item.todoBusinessType"
                  :value="item.todoBusinessType"
                  :disabled="item.disabled"
                >
                  {{ item.todoTypeText }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col class="gutter-row" :span="12">
            <a-form-item label="告警时长：">
              <a-input-number
                v-model="state.alarmDuration"
                :min="0"
                :max="1000000000"
                :precision="0"
                style="--content: '小时'"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="超时时长：">
              <a-input-number
                v-model="state.timeoutDuratiojn"
                :min="0"
                :max="1000000000"
                :precision="0"
                style="--content: '小时'"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="text-center mt20">
        <a-space>
          <a-button
            type="primary"
            @click="confirmSlaConfigHandler"
            :loading="state.loadingConfirmAllocationBtn"
          >
            确定
          </a-button>
          <a-button @click="state.showCreateSlaConfigModal = false">
            取消
          </a-button>
        </a-space>
      </div>
    </a-modal>
  </div>
</template>
<script>
import {
  todo_sla_config_add,
  todo_sla_config_update,
  todo_sla_delete_post
} from 'server/modules/7537'

export default {
  name: 'SlaConfigModal',
  props: ['showSlaConfigModal', 'slaTypeOptions'],
  data() {
    return {
      state: {
        createSlaConfigBtnDisabled: false,
        loadingCreateSlaConfigBtn: false,
        showCreateSlaConfigModal: false,
        loadingConfirmAllocationBtn: false,
        slaTableId: null,
        slaType: [],
        alarmDuration: null,
        timeoutDuratiojn: null
      },
      updateNodeColumns: [
        {
          title: '流程类型',
          dataIndex: 'todoTypeText',
          key: 'todoTypeText'
        },
        {
          title: '告警时长（H）',
          dataIndex: 'alarmDuration',
          key: 'alarmDuration'
        },
        {
          title: '超时时长（H）',
          dataIndex: 'timeoutDuratiojn',
          key: 'timeoutDuratiojn'
        },
        {
          title: '操作',
          dataIndex: 'operator',
          key: 'operator',
          width: '180px',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  },
  watch: {
    showSlaConfigModal(val) {
      if (val) {
        this.state.loadingCreateSlaConfigBtn = true
        // 禁用
        this.$nextTick(() => {
          const unwatch = this.$watch(
            '$refs.slaConfigTable.spinning',
            val => {
              if (!val) {
                const element = document.querySelector(
                  '.slaTable div.ant-table-body'
                )
                if (element.scrollHeight > element.clientHeight) {
                  const tableHeader = document.querySelector(
                    '.slaTable div.ant-table-header'
                  )
                  tableHeader.style.overflowY = 'scroll'
                } else {
                  const tableHeader = document.querySelector(
                    '.slaTable div.ant-table-header'
                  )
                  tableHeader.style.overflowY = 'hidden'
                }
                let count = 0
                this.slaTypeOptions.forEach(item1 => {
                  try {
                    this.$refs.slaConfigTable.tableDatas.forEach(item2 => {
                      if (item2.todoBusinessType === item1.todoBusinessType) {
                        item1.disabled = true
                        count++
                        throw new Error('已存在')
                      } else {
                        item1.disabled = false
                      }
                    })
                  } catch (error) {}
                })
                if (count === this.slaTypeOptions.length) {
                  this.state.createSlaConfigBtnDisabled = true
                } else {
                  this.state.createSlaConfigBtnDisabled = false
                }
                this.state.loadingCreateSlaConfigBtn = false
                if (unwatch) unwatch()
              }
            },
            { immediate: true, deep: true }
          )
        })
      }
    },
    'state.showCreateSlaConfigModal'(val) {
      if (!val) {
        this.state.slaTableId = null
        this.state.slaType = []
        this.state.alarmDuration = null
        this.state.timeoutDuratiojn = null
      }
    }
  },
  methods: {
    createSlaConfig() {
      this.state.showCreateSlaConfigModal = true
    },
    updateSlaConfig(record) {
      this.state.slaTableId = record.id
      this.state.slaType = record.todoBusinessType
      this.state.alarmDuration = record.alarmDuration
      this.state.timeoutDuratiojn = record.timeoutDuratiojn
      this.state.showCreateSlaConfigModal = true
    },
    deleteSlaConfig(record) {
      this.state.loadingConfirmAllocationBtn = true
      todo_sla_delete_post({
        id: record.id
      })
        .then(({ success, retInfo, data }) => {
          if (success) {
            this.$message.success(data)
            this.state.createSlaConfigBtnDisabled = false
            this.$refs.slaConfigTable.refresh()
            const unwatch = this.$watch(
              '$refs.slaConfigTable.spinning',
              val => {
                if (!val) {
                  const element = document.querySelector(
                    '.slaTable div.ant-table-body'
                  )
                  if (element.scrollHeight > element.clientHeight) {
                    const tableHeader = document.querySelector(
                      '.slaTable div.ant-table-header'
                    )
                    tableHeader.style.overflowY = 'scroll'
                  } else {
                    const tableHeader = document.querySelector(
                      '.slaTable div.ant-table-header'
                    )
                    tableHeader.style.overflowY = 'hidden'
                  }
                  this.slaTypeOptions.forEach(item1 => {
                    try {
                      this.$refs.slaConfigTable.tableDatas.forEach(item2 => {
                        if (item2.todoBusinessType === item1.todoBusinessType) {
                          item1.disabled = true
                          throw new Error('已存在')
                        } else {
                          item1.disabled = false
                        }
                      })
                    } catch (error) {}
                  })
                  if (unwatch) unwatch()
                }
              }
            )
          }
        })
        .finally(() => {
          this.state.loadingConfirmAllocationBtn = false
        })
    },
    deleteSlaConfigCancel() {
      this.$message.info('取消删除')
    },
    async confirmSlaConfigHandler() {
      this.state.loadingConfirmAllocationBtn = true
      let requestUrl = todo_sla_config_add
      if (this.state.slaTableId) {
        requestUrl = todo_sla_config_update
      }
      const { success, retInfo, data } = await requestUrl({
        id: this.state.slaTableId,
        todoBusinessType: this.state.slaType,
        todoTypeCode: this.slaTypeOptions.find(
          item => item.todoBusinessType === this.state.slaType
        ).todoTypeCode,
        todoTypeText: function () {
          for (const item of this.slaTypeOptions) {
            if (item.todoBusinessType === this.state.slaType) {
              return item.todoTypeText
            }
          }
        }.bind(this)(),
        alarmDuration: this.state.alarmDuration,
        timeoutDuratiojn: this.state.timeoutDuratiojn
      })
      this.state.loadingConfirmAllocationBtn = false
      if (success) {
        this.$message.success(data)
        let count = 0
        this.$refs.slaConfigTable.refresh()
        const unwatch = this.$watch('$refs.slaConfigTable.spinning', val => {
          if (!val) {
            const element = document.querySelector(
              '.slaTable div.ant-table-body'
            )
            if (element.scrollHeight > element.clientHeight) {
              const tableHeader = document.querySelector(
                '.slaTable div.ant-table-header'
              )
              tableHeader.style.overflowY = 'scroll'
            } else {
              const tableHeader = document.querySelector(
                '.slaTable div.ant-table-header'
              )
              tableHeader.style.overflowY = 'hidden'
            }
            this.slaTypeOptions.forEach(item1 => {
              try {
                this.$refs.slaConfigTable.tableDatas.forEach(item2 => {
                  if (item2.todoBusinessType === item1.todoBusinessType) {
                    item1.disabled = true
                    count++
                    throw new Error('已存在')
                  } else {
                    item1.disabled = false
                  }
                })
              } catch (error) {}
            })
            if (unwatch) unwatch()
            if (count === this.slaTypeOptions.length) {
              this.state.createSlaConfigBtnDisabled = true
            } else {
              this.state.createSlaConfigBtnDisabled = false
            }
          }
        })
      } else {
        this.$message.error(retInfo)
      }
      this.state.showCreateSlaConfigModal = false
    },
    closeModal() {
      this.$emit('closeModal')
    }
  }
}
</script>
<style lang="less" scoped>
:deep(.sla-type-form-item .ant-form-item) {
  width: 100%;
  display: flex;

  .ant-form-item-control-wrapper {
    flex-grow: 1;
  }

  .ant-form-item-children {
    display: flex;

    .ant-input-number {
      display: inline-table;
      flex-grow: 1;

      .ant-input-number-handler-wrap {
        display: none;
      }

      &::after {
        content: var(--content);
        color: #909399;
        background-color: #f5f7fa;
        vertical-align: middle;
        display: table-cell;
        position: relative;
        border-radius: 4px;
        border-left: 0;
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
        padding: 0 20px;
        width: 1px;
        white-space: nowrap;
      }
    }
  }
}
:deep(.ant-table-scroll .ant-table-body) {
  overflow: auto !important;
}
</style>
